package com.linkallcloud.web.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.linkallcloud.core.dto.Result;
import com.linkallcloud.core.exception.Exceptions;
import com.linkallcloud.core.www.utils.WebUtils;

public class ExceptionFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			if (WebUtils.isAjax((HttpServletRequest) request)) {
				HttpServletResponse resp = (HttpServletResponse) response;
				resp.setCharacterEncoding("utf-8");
				resp.setContentType("application/json; charset=utf-8");
				PrintWriter writer = resp.getWriter();
				Result<Object> r = Exceptions.makeErrorResult(e);
				writer.write(JSON.toJSONString(r));
			} else {
				// 异常捕获，发送到error controller
				request.setAttribute("filter.error", e);
				// 将异常分发到/error/exthrow控制器
				request.getRequestDispatcher("/error/exthrow").forward(request, response);
			}
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

}
